/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */
package com.tengtong.duang.commons.convert.support;

import com.tengtong.duang.commons.base.AssertUtils;
import com.tengtong.duang.commons.convert.ConditionalConverter;
import com.tengtong.duang.commons.utils.ClassUtils;

/**
 * 字符串类型转换器，可以将下面的内容转为字符串：
 *  
 *  1) 数值类型
 *  
 *  2）字符串类型
 *  
 *  3）布尔类型
 * 
 * @author jai
 *
 */
public class StringGenericConverter implements ConditionalConverter {
	
	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#matches(java.lang.Class, java.lang.Class)
	 */
	@Override
	public boolean matches(Class<?> sourceType, Class<?> targetType) {
		AssertUtils.notNull(sourceType, "sourceType 不能为 null.");
		AssertUtils.notNull(targetType, "targetType 不能为 null.");
		
		if(!String.class.equals(targetType)){
			return false;
		}
		
		if(ClassUtils.isInheritance(sourceType, Number.class)){
			return true;
		}
		
		if(Boolean.class.equals(sourceType)){
			return true;
		}
		
		if(String.class.equals(sourceType)){
			return true;
		}
		
		return false;
	}

	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#convert(java.lang.Object, java.lang.Class)
	 */
	@Override
	public Object convert(Object source, Class targetType) {
		if(source != null && targetType != null){
			Class<?> sourceType = source.getClass();

			if(String.class.equals(sourceType)){
				return (String)source;
			}
			
			if(ClassUtils.isInheritance(sourceType, Number.class)){
				return String.valueOf(source);
			}
			
			if(Boolean.class.equals(sourceType)){
				return String.valueOf(source);
			}
		}
		
		return null;
	}

}
